package com.lbw.chatMemory.repository;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lbw.entity.po.ChatConversationIds;
import com.lbw.entity.po.ChatHistory;
import com.lbw.service.IChatConversationIdsService;
import com.lbw.service.IChatHistoryService;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.memory.ChatMemoryRepository;
import org.springframework.ai.chat.messages.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Component
@Slf4j
public class MySqlMemoryRepository implements ChatMemoryRepository {

    @Autowired
    private IChatHistoryService chatHistoryService;

    @Autowired
    private IChatConversationIdsService chatConversationIdsService;


    /**
     * 保存会话id
     * @param conversationId
     */
    public void saveConversationId(String conversationId) {
        // 先检查是否已存在该 conversationId
        ChatConversationIds existing = chatConversationIdsService.getOne(
                new LambdaQueryWrapper<ChatConversationIds>().eq(ChatConversationIds::getConversationId, conversationId)
        );

        // 如果不存在，则保存
        if (existing == null) {
            ChatConversationIds chatConversationIds = new ChatConversationIds(conversationId);
            chatConversationIdsService.save(chatConversationIds);
        }
    }

    /**
     * 获取所有会话列表id
     * @return
     */
    @Override
    public List<String> findConversationIds() {
        List<String> conversationIds = chatConversationIdsService.list()
                .stream()
                .map(ChatConversationIds::getConversationId)
                .toList();
        return conversationIds;
    }

    /**
     * 根据会话id获取所有消息
     * @param conversationId
     * @return
     */
    @Override
    public List<Message> findByConversationId(String conversationId) {
        // 查询数据库记录
        List<ChatHistory> histories = chatHistoryService.list(new QueryWrapper<ChatHistory>()
                .eq("conversation_id", conversationId));
        //log.info("数据库查询到的原始数据，histories:{}", histories);

        // 转换为Message对象
        List<Message> messages = new ArrayList<>();
        for (ChatHistory history : histories) {
            // 根据MessageType创建具体的消息类型
            if (MessageType.USER.name().equals(history.getRole())) {
                messages.add(new UserMessage(history.getText()));
            } else if (MessageType.ASSISTANT.name().equals(history.getRole())) {
                messages.add(new AssistantMessage(history.getThink() +history.getText()));
            } else {
                messages.add(new SystemMessage(history.getText()));
            }
        }
        //log.info("转换后的数据格式，messages:{}", messages);
        return messages;
    }

    /**
     * 根据会话id保存所有消息
     * @param conversationId
     * @param messages
     */
    @Override
    public void saveAll(String conversationId, List<Message> messages) {
        List<ChatHistory> histories = new ArrayList<>();
        messages.forEach(message -> {
            ChatHistory chatHistory = new ChatHistory();
            chatHistory.setConversationId(conversationId);
            chatHistory.setRole(message.getMessageType().name());

            FilterResult result = filterThinkContent(message.getText());
            chatHistory.setText(result.getFilteredText());

            // 将多个think内容合并后保存（例如用换行符分隔）
            if (!result.getThinks().isEmpty()) {
                String mergedThinks = String.join("\n", result.getThinks());
                chatHistory.setThink(mergedThinks);
            }

            histories.add(chatHistory);
        });

        try {
            chatHistoryService.saveBatch(histories);
        } catch (Exception e) {
            log.error("批量保存失败：{}", e.getMessage());
        }
    }

    // 新增过滤方法（适配<think>标签）
    public static FilterResult filterThinkContent(String text) {
        List<String> thinks = new ArrayList<>();
        String regExThink = "(<think[^>]*>.*?</think>)";
        Pattern pattern = Pattern.compile(regExThink, Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
        Matcher matcher = pattern.matcher(text);

        // 提取所有think内容
        while (matcher.find()) {
            thinks.add(matcher.group(1));
        }

        // 移除think标签得到过滤后的文本
        String filteredText = matcher.replaceAll("").trim();
        return new FilterResult(filteredText, thinks);
    }

    // 新增静态内部类（用于封装过滤后的文本和思考内容）
    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    public static class FilterResult {
        private String filteredText;
        private List<String> thinks;

    }

    /**
     * 根据会话id删除所有消息
     * @param conversationId
     */
    @Override
    public void deleteByConversationId(String conversationId) {
        chatHistoryService.remove(
                new LambdaQueryWrapper<ChatHistory>()
                        .eq(ChatHistory::getConversationId, conversationId));
        chatConversationIdsService.remove(
                new LambdaQueryWrapper<ChatConversationIds>()
                        .eq(ChatConversationIds::getConversationId, conversationId));
    }
}
